題目:
Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
給定一binary tree的root,回傳其所有左葉值的和
這題自己寫一個判斷Node是不是leaf的函式會方便不少
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
def isleaf(root):
if root and root.left==None and root.right==None:
return True
else:
return False
ans=[0]
def x(root):
if not root:
return
if isleaf(root.left):
ans[0]=ans[0]+root.left.val
else:
x(root.left)
if not isleaf(root.right):
x(root.right)
x(root)
return ans[0]
先自製一個判斷Node是不是leaf的函式
接著開始遞迴,若一開始root是None直接return
利用事先寫好的函式判斷root.left和root.right是不是leaf
若root.left是leaf則將其值加到ans[0]
同時因為它不會有左leaf,所以不用往下探索了
同理,若root.right是leaf,也不用往下探索
最後回傳ans[0]
最後執行時間28ms(faster than 98.38%)
那我們下題見